package com.haixiaoke.saas.enterprise.contract.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.haixiaoke.saas.account.yima.config.YiMaConfiguration;
import com.haixiaoke.saas.account.yima.doman.YiMaDto;
import com.haixiaoke.saas.account.yima.service.YiMaService;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.constant.ProprietorConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.poi.ExcelUtil;
import com.haixiaoke.saas.contract.domain.Proprietor;
import com.haixiaoke.saas.contract.domain.ProxyService;
import com.haixiaoke.saas.contract.service.IProprietorService;
import com.haixiaoke.saas.contract.service.IProxyServiceService;
import com.haixiaoke.saas.system.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 代理服务信息Controller
 *
 * @author xiaolong
 * @date 2024-06-06
 */
@RestController
@RequestMapping("/enterprise/contract/proxyService")
@Slf4j
public class EnterpriseProxyServiceController extends BaseController {
    @Autowired
    private IProxyServiceService proxyServiceService;

    @Autowired
    private YiMaService yiMaService;

    @Autowired
    private YiMaConfiguration yiMaConfiguration;
    @Autowired
    private IProprietorService proprietorService;

    /**
     * 查询代理服务信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ProxyService proxyService) {
        startPage();
        List<ProxyService> list = proxyServiceService.selectProxyServiceList(proxyService);
        return getDataTable(list);
    }

    /**
     * 导出代理服务信息列表
     */
    @PostMapping("/export")
    @RepeatSubmit
    public void export(HttpServletResponse response, ProxyService proxyService) {
        List<ProxyService> list = proxyServiceService.selectProxyServiceList(proxyService);
        ExcelUtil<ProxyService> util = new ExcelUtil<ProxyService>(ProxyService.class);
        util.exportExcel(response, list, "代理服务信息数据");
    }


    /**
     * 获取代理服务信息详细信息
     */
    @GetMapping(value = "/{proprietorId}")
    public AjaxResult getInfo(@PathVariable("proprietorId") Long proprietorId) {
        return success(proxyServiceService.selectProxyServiceByProprietorId(proprietorId));
    }


    /**
     * 新增代理服务信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proxyService:add')")
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestBody ProxyService proxyService) {
        proxyService.setCreateBy(getUserId().toString());
        return toAjax(proxyServiceService.insertProxyService(proxyService));
    }

    /**
     * 代理服务信息-结算银行卡
     */
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody @Valid ProxyService proxyService) {
        proxyService.setUpdateBy(getUserId().toString());
        return toAjax(proxyServiceService.updateProxyService(proxyService));
    }

    /**
     * 删除代理服务信息
     */
    @DeleteMapping("/{proxyServiceIds}")
    @RepeatSubmit
    public AjaxResult remove(@PathVariable Long[] proxyServiceIds) {
        return toAjax(proxyServiceService.deleteProxyServiceByProxyServiceIds(proxyServiceIds));
    }

    /**
     * 扫码认证
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proxyService:scanAuth')")
    @GetMapping("/scanAuth/{proxyServiceId}")
    public AjaxResult scanAuth(@PathVariable Long proxyServiceId) {
        String authUrl = proxyServiceService.scanAuth(proxyServiceId);
        return StrUtil.isBlank(authUrl) ? AjaxResult.error("认证失败，请稍后再试") :
                AjaxResult.success("操作成功", authUrl);
    }


    /**
     * 业主开户
     */
    // @PreAuthorize("@ss.hasPermi('enterprise:proxyService:ownerOpenAccount')")
    @PostMapping("/ownerOpenAccount/{proprietorId}")
    @Transactional
    public AjaxResult ownerOpenAccount(@RequestBody YiMaDto yiMaDto, @PathVariable Long proprietorId) {
        String type = yiMaDto.getType();
        ProxyService proxyService = proxyServiceService.selectProxyServiceByProprietorId(proprietorId);
        if (proxyService == null) {
            return AjaxResult.error("该服务不存在");
        }
        Long merchantId;
        // 企业
        if (StrUtil.equals(type, "1")) {
            merchantId = yiMaService.merchantEntregister(yiMaDto);
        } else {
            // 个人
            merchantId = yiMaService.merchantIndividual(yiMaDto);
        }
        proxyService.setYmMerchantId(merchantId);
        proxyService.setSplitMerchantStatus(ProprietorConstants.MERCHANT_STATUS_ACCOUNT_OPENED_UNBOUND);
        return toAjax(proxyServiceService.updateProxyService(proxyService));
    }

    /**
     * 业主商户绑定
     */
    // @PreAuthorize("@ss.hasPermi('enterprise:proxyService:ownerBindMerchant')")
    @PostMapping("/ownerBindMerchant/{proprietorId}")
    @Transactional
    public AjaxResult ownerBindMerchant(@RequestBody YiMaDto yiMaDto, @PathVariable Long proprietorId) {
        ProxyService proxyService = proxyServiceService.selectProxyServiceByProprietorId(proprietorId);
        if (proxyService == null) {
            return AjaxResult.error("该服务不存在");
        }
        Long ymMerchantId = proxyService.getYmMerchantId();
        yiMaDto.setMerchantId(ymMerchantId);
        String s = yiMaService.merchantOpen(yiMaDto);
        if (yiMaConfiguration.checkResult(s)) {

            Proprietor proprietor = proprietorService.selectProprietorByProprietorId(proprietorId);
            if (proprietor == null) {
                throw new ServiceException("该业主不存在");
            }

            YiMaDto terminalBind = new YiMaDto();
            terminalBind.setStoreId(proprietor.getProprietorMobile());
            terminalBind.setStoreName(proprietor.getProprietorName());
            terminalBind.setUserId(proprietor.getConUserId().toString());
            String terminalBindResult = yiMaService.terminalBind(terminalBind);
            if (!yiMaConfiguration.checkResult(terminalBindResult)) {
                log.error("终端绑定失败：{}", terminalBindResult);
                throw new ServiceException("终端绑定失败");
            }

            proxyService.setSplitMerchantStatus(ProprietorConstants.MERCHANT_STATUS_ACCOUNT_OPENED_BOUND);
            proxyService.setBankAccount(yiMaDto.getCardNo());
            proxyService.setBankName(yiMaDto.getParentBankName());
            proxyService.setBankCode(yiMaDto.getParentBankCode());
            proxyService.setBankBranchCode(yiMaDto.getBranchBankCode());
            proxyService.setBankBranch(yiMaDto.getBranchBankName());
            proxyService.setBankAccountType(yiMaDto.getSettleType());
            proxyServiceService.updateProxyService(proxyService);

            if (ProprietorConstants.ELECTRONIC_VISA_STATUS_AUTH.equals(proxyService.getElectronicVisaStatus())) {
                proprietor.setProprietorId(proxyService.getProprietorId());
                proprietor.setProxyServiceStatus(ProprietorConstants.PROXY_SERVICE_STATUS_FINISH);
                proprietorService.updateProprietor(proprietor);
            }

            return AjaxResult.success("操作成功");
        } else {
            log.error("业主商户绑定失败：{}", s);
            Map<String, Object> map = JSONUtil.toBean(s, Map.class);
            Map<String, Object> message = JSONUtil.toBean(ObjectUtil.toString(map.get("result")), Map.class);
            return AjaxResult.error(ObjectUtil.toString(message.get("comment")));
        }
    }
}
